<script>
import path from "path";
import { asyncRoutes } from "@/router";
import { isExternal } from "@/utils/validate";

export default {
  name: "ErrPage",
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      vm.hasPage(
        asyncRoutes.slice(0, asyncRoutes.length - 1),
        to.redirectedFrom,
        ""
      )
        ? vm.$router.replace("/401")
        : vm.$router.replace("/404");
    });
  },
  methods: {
    hasPage(list, redirectedFrom, basePath) {
      return list.some((route) => {
        if (this.resolvePath(route.path, basePath) === redirectedFrom) {
          return true;
        } else if (route.children) {
          return this.hasPage(
            route.children,
            redirectedFrom,
            this.resolvePath(route.path, basePath)
          );
        }
      });
    },
    resolvePath(routePath, basePath) {
      if (isExternal(routePath)) {
        return routePath;
      }
      if (isExternal(basePath)) {
        return basePath;
      }
      return path.resolve(basePath || "", routePath || "");
    },
  },
  render: function (h) {
    return h(); // avoid warning message
  },
};
</script>
